<!-- eslint-disable vue/max-attributes-per-line -->
<!-- eslint-disable vue/html-self-closing -->
<template>
  <el-card shadow="always" style="margin: 20px">
    <el-form label-width="80px" :inline="true" size="medium">
      <el-form-item label="">
        <el-input v-model="input" placeholder="用户名" size="small"></el-input>
      </el-form-item>
      <el-button type="primary" icon="el-icon-search" size="small" @click="search">查询</el-button>
      <el-button size="small" @click="clear">清空</el-button>
      <el-button v-hasBtn="'testButton'" type="info" size="small">测试按钮权限控制</el-button>
    </el-form>
    <el-button type="primary" size="small" @click="addUser">添加</el-button>
    <el-button type="danger" size="small" :disabled="!multipleSelection.length" @click="batchDelete">批量删除</el-button>
    <el-table v-loading="loading" :data="userList" tooltip-effect="dark" style="width: 100%; margin-top: 20px" border
      stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column label="序号" width="80" align="center" type="index">

      </el-table-column>
      <el-table-column prop="username" label="用户名">

      </el-table-column>
      <el-table-column prop="nickName" label="用户昵称">

      </el-table-column>
      <el-table-column prop="roleName" label="角色列表">

      </el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间">

      </el-table-column>
      <el-table-column prop="gmtModified" label="更新时间">

      </el-table-column>

      <el-table-column label="操作" align="center">
        <template v-slot="{row}">
          <el-button type="info" icon="el-icon-user-solid" size="mini" @click="setRole(row)"></el-button>
          <el-button type="primary" icon="el-icon-edit-outline" size="mini" @click="updateUser(row)"></el-button>

          <el-popconfirm style="margin-left: 10px;" :title="`确定删除${row.username}吗?`" @onConfirm="confirmDelete(row)">
            <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini"></el-button>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>
    <el-pagination style="margin-top: 20px" :current-page="currentPage" :page-sizes="[5, 10, 20, 30]" :page-size="5"
      layout="prev, pager, next, jumper, ->, sizes, total" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible="isShowAddDialog">
      <el-form ref="formData" label-width="100px" :rules="addRules" :model="formData" :inline="false" size="normal">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="formData.nickName"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="formData.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="isShowAddDialog = false">取 消</el-button>
        <el-button type="primary" size="small" @click="addConfirm('formData')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible="isShowUpdateDialog">
      <el-form ref="updateFormData" label-width="100px" :rules="updateRules" :model="updateFormData" :inline="false"
        size="normal">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="updateFormData.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="updateFormData.nickName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="isShowUpdateDialog = false">取消</el-button>
        <el-button type="primary" size="small" @click="updateConfirm('updateFormData')">确定</el-button>
      </span>
    </el-dialog>

    <!-- 设置角色对话框 -->
    <el-dialog title="设置角色" :visible="isShowSetRole">
      <el-form ref="setRoleFormData" label-width="100px" :model="setRoleFormData" :inline="false" size="normal">
        <el-form-item label="用户名">
          <el-input v-model="setRoleFormData.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
          </el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="roleInfo.checkIdList" @change="handleCheckedRolesChange">
            <el-checkbox v-for="roleList in roleInfo.allRolesList" :key="roleList.id" :label="roleList.id">
              {{roleList.roleName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="primary" size="small" @click="doAssign">保存</el-button>
        <el-button size="small" @click="isShowSetRole = false">取消</el-button>
      </span>
    </el-dialog>

  </el-card>
</template>
<script>
import request from '@/api/userManagement'
export default {
  name: 'User',
  data() {
    return {
      loading: false,
      currentPage: 1,
      limit: 5,
      total: 0,
      input: '',
      userList: [],
      formData: {
        username: '',
        nickName: '',
        password: ''
      },
      updateFormData: {
        username: '',
        nickName: ''
      },
      setRoleFormData: {
        username: ''
      },
      multipleSelection: [],
      // 是否展示添加的dialog
      isShowAddDialog: false,
      isShowUpdateDialog: false,
      isShowSetRole: false,
      // 表单校验规则
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'change' }
        ]
      },
      updateRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'change' }
        ]
      },
      checkAll: false,
      roleInfo: {
        allRolesList: [],
        checkIdList: [],
        userId: ''
      },
      isIndeterminate: true
    }
  },
  async mounted() {
    await this.getUserList()
  },
  methods: {
    handleSizeChange(val) {
      this.limit = val
      this.getUserList()
    },
    async handleCurrentChange(val) {
      if (this.input.trim()) {
        await this.getUserList(val, this.limit, this.input.trim())
      } else {
        await this.getUserList(val)
      }
    },
    async getUserList(page = 1, limit = this.limit, username) {
      this.loading = true
      this.currentPage = page
      const result = await request.getUserList(this.currentPage, limit, username)
      this.total = result.total
      this.userList = result.items
      this.loading = false
      // console.log(result)
    },
    async search() {
      await this.getUserList(this.currentPage, this.limit, this.input.trim())
    },
    clear() {
      this.input = ''
      this.getUserList()
    },
    addConfirm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          try {
            await request.addUser(this.formData)
            this.$message({
              message: '添加成功!',
              type: 'success'
            })
            this.isShowAddDialog = false
            this.getUserList()
          } catch (error) {
            this.$message({
              message: `添加失败!错误码: ${error}`,
              type: 'error'
            })
          }
        } else {
          this.$message({
            message: '表单校验失败!',
            type: 'error'
          })
          return false
        }
      })
    },
    addUser() {
      this.formData = {
        username: '',
        nickName: '',
        password: ''
      }
      this.$nextTick(() => {
        this.$refs.formData.clearValidate(['username', 'password'])
      })
      this.isShowAddDialog = true
    },
    updateUser(row) {
      this.updateFormData = { ...row }
      this.isShowUpdateDialog = true
    },
    updateConfirm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          try {
            await request.updateUser(this.updateFormData)
            this.$message({
              message: '修改成功!',
              type: 'success'
            })
            this.isShowUpdateDialog = false
            this.getUserList(this.page)
          } catch (error) {
            this.$message({
              message: `修改失败!错误码: ${error}`,
              type: 'error'
            })
          }
        } else {
          this.$message({
            message: '表单校验失败!',
            type: 'error'
          })
          return false
        }
      })
    },
    async confirmDelete(row) {
      try {
        await request.deleteUser(row.id)
        this.$message({
          message: '删除成功!',
          type: 'success'
        })
        this.getUserList()
      } catch (error) {
        this.$message({
          message: `删除失败!错误码: ${error}`,
          type: 'error'
        })
      }
    },
    async setRole(row) {
      this.setRoleFormData.username = row.username
      try {
        this.roleInfo.userId = row.id
        const result = await request.getRoleInfoByUserId(row.id)
        this.roleInfo.allRolesList = result.allRolesList.map(item => ({
          id: item.id,
          roleName: item.roleName
        }))
        this.roleInfo.checkIdList = result.assignRoles.map(item => item.id)
        this.isShowSetRole = true
      } catch (error) {
        this.$message({
          message: '获取用户角色信息失败!',
          type: 'error'
        })
      }
    },
    async doAssign() {
      await request.doAssign(this.roleInfo.userId, this.roleInfo.checkIdList.join(','))
      this.getUserList(this.page)
      this.isShowSetRole = false
    },

    handleCheckAllChange(val) {
      console.log(val)
      this.roleInfo.checkIdList = val ? this.roleInfo.allRolesList.map(item => item.id) : []
      this.isIndeterminate = false
    },
    handleCheckedRolesChange(value) {
      console.log(value)
      const checkedCount = value.length
      this.checkAll = checkedCount === this.roleInfo.allRolesList.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.roleInfo.allRolesList.length
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.id)
    },
    async batchDelete() {
      const batchDeleteList = []
      this.multipleSelection.forEach(async item =>
        batchDeleteList.push(request.deleteUser(item))
      )
      try {
        await Promise.all(batchDeleteList)
        this.$message({
          message: '批量删除成功!',
          type: 'success'
        })
        this.getUserList(this.page)
      } catch (error) {
        this.$message({
          message: '批量删除失败!',
          type: 'error'
        })
        this.getUserList(this.page)
      }
    }
  }
}
</script>

<style scoped>

</style>
